﻿using ConfigInfoWebPlatform.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ConfigInfoWebPlatform.API.DBCommon
{
    /// <summary>
    /// 打包记录数据层
    /// </summary>
    public class DAL_PackagRecord
    {
        private IFreeSql freeSql;

        /// <summary>
        /// 打包记录数据层
        /// </summary>
        /// <param name="dbcode"></param>
        public DAL_PackagRecord(string dbcode)
        {
            freeSql = FreesqlFactory.GetFreeSql(dbcode);
        }

        /// <summary>
        /// 获取打包记录列表数据
        /// </summary>
        /// <returns></returns>
        public List<PackagRecord> GetPackags()
        {
            var query = new List<PackagRecord>();
            try
            {
                query = freeSql.Select<PackagRecord>()
                             .OrderByDescending(x => x.CreateTime)
                             .ToList();
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }
            return query;
        }

        /// <summary>
        /// 添加打包记录数据
        /// </summary>
        public int InsertPaskagRecord(PackagRecord model)
        {
            var result = freeSql.Insert<PackagRecord>(model).ExecuteAffrows();
            return result;
        }

        /// <summary>
        /// 更新打包记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdatePaskagRecord(PackagRecord model)
        {
            var result = freeSql.Update<PackagRecord>(model).SetSourceIgnore(model, col => col == null).ExecuteAffrows();
            return result;
        }

        /// <summary>
        /// 修改打包记录状态
        /// </summary>
        public int UpdatePaskagStatus(string id,int status)
        {
            var result = freeSql.Update<PackagRecord>()
                              .Set(x => x.PackagStatus, status)
                              .Where(x => x.Id == id)
                              .ExecuteAffrows();
            return result;
        }

        /// <summary>
        /// 根据Id获取打包记录信息
        /// </summary>
        public PackagRecord GetPaskagRecordById(string id)
        {
            var query = freeSql.Select<PackagRecord>()
                             .Where(x => x.Id == id)
                             .ToOne();
            return query;
        }

        /// <summary>
        /// 获取流程树
        /// </summary>
        /// <returns></returns>
        public List<ProcessNavicatTreeModel> GetProcessTree()
        {
            List<ProcessDocModel> allDatas = new List<ProcessDocModel>();
            //流程数据
            var processList = freeSql.Select<ProgramNavicat>()
                                   .Where(x => x.Id >= 1001000000000000)
                                   .Where(x => x.Id < 1002000000000000)
                                   .Where(x => x.Navicatflag == 1)
                                   .ToList(x => new ProcessDocModel
                                   {
                                       Id = x.Id.ToString(),
                                       ParentId = x.ParentId.ToString(),
                                       Level = x.Level == 2 ? "1" : (x.Level == 3 ? "2" : ""),
                                       Name = x.Name,
                                       Directory = x.Directory
                                   });
            if (processList != null && processList.Any())
                allDatas.AddRange(processList);
            //文书数据
            var docList = freeSql.Select<ConfigFiles>()
                                 .Where(x => x.Path.Contains("config/processconfig/analysisprocessconfig"))
                                 .Where(x => x.Level == 3)
                                 .Where(x => x.Ctype == "D")
                                 .ToList(x => new ProcessDocModel
                                 {
                                     Id = x.Currentid,
                                     ParentId = x.Programid.ToString(),
                                     Level = "3",
                                     Name = x.Name,
                                     Directory = x.Path
                                 });
            var dataSources = freeSql.Select<DataSource>().ToList();
            if (docList != null && docList.Any())
            {
                foreach (var item in docList)
                {
                    var caseTypePath = Path.GetDirectoryName(item.Directory);
                    var caseType = Path.GetFileName(caseTypePath);
                    var source = dataSources.FirstOrDefault(x => x.CaseTypeCode.ToLower() == caseType && x.Code.ToLower() == item.Name.ToLower());
                    if (source != null && !string.IsNullOrWhiteSpace(source.Name))
                        item.Name = $"{item.Name}：{source.Name}";
                }
                allDatas.AddRange(docList);
            }
            var firstNavs = allDatas.Where(x => x.ParentId == "1001000000000000")
                                            .Select(x => new ProcessNavicatTreeModel()
                                            {
                                                Id = x.Id,
                                                Name = x.Name,
                                                Directory = x.Directory
                                            }).ToList();
            foreach (var first in firstNavs)
            {
                GetProgramNavicatChilder(allDatas, first);
            }
            return firstNavs;
        }

        /// <summary>
        /// 加载子级数据
        /// </summary>
        /// <param name="allNavs">所有数据</param>
        /// <param name="parent">父级数据</param>
        private void GetProgramNavicatChilder(List<ProcessDocModel> allNavs, ProcessNavicatTreeModel parent)
        {
            if (parent != null)
            {
                var childers = allNavs.Where(x => x.ParentId == parent.Id).ToList();
                if (childers.Any())
                {
                    parent.Childrens = childers.Select(x => new ProcessNavicatTreeModel()
                    {
                        Id = x.Id,
                        Name = x.Name,
                        Directory = x.Directory
                    }).ToList();
                    foreach (var nav in parent.Childrens)
                    {
                        GetProgramNavicatChilder(allNavs, nav);
                    }
                }
            }
        }
    }
}
